<?php
/**
 * Created by phpstorem.
 * User: yangakw@qq.com
 * Sign: 猥琐发育，别浪
 * Date: 2017/10/5 0005
 * Time: 下午 10:01
 */

namespace src;


use conf\Config;

class App
{
    /** @var  DownLoad */
    public $download;
    /** @var  Parse */
    public $parse;
    public function main(){
        $this->download=new DownLoad();
        $this->parse=new Parse( $this->download );
        #初始化
        $this->__init__();
    }

    /**
     * 线程开启
     */
    public function run(){
        BEGIN:
        $doing = Queue::doing();
        $num = count($doing);
        #开始从队列中取出数据进行处理
        echo "begin analysis $num page\n";
        /** @var Item $will_do */
        foreach($doing as $will_do){
            $this->parse->analysls($will_do);
        }
        #运行一段时间休息
        echo "analysis complste $num , now i need sleep ".Config::SLEEP_TIME."\n";

        ##对已知错误处理
        $this->error_handle();
        #完成的操作
        $this->done_handle();
        sleep(Config::SLEEP_TIME);
        goto BEGIN;
    }
    public function __init__(){
        /**
         * 队列第一条数据
         */
        $item = $this->download->get( Config::DOMAIN ,"web");
        if($item instanceof Item){
            Queue::doing($item);
            echo "begin to job !!! \n\n\n\n\n";
            $this->run();
        }
    }

    /**
     * 对已知错误处理
     */
    public function error_handle(){
        if(count(Queue::$error_data) > Config::MAX_ERROR_DATA_SIZE){
            foreach(Queue::$error_data as $key=>$item){
                unset(Queue::$error_data[$key]);
            }
        }
    }

    /**
     * 完成的操作
     */
    public function done_handle(){
        if(count(Queue::$done_data) > Config::MAX_DONE_DATA_SIZE){
            foreach(Queue::$done_data as $key=>$item){
                unset(Queue::$done_data[$key]);
            }
        }
    }
}